using System;
using CommandSystem;
using RgCore.Modules;
using Utils.NonAllocLINQ;

namespace RgCore.Commands.ModuleCommands
{
    public class Unload : ICommand
    {
        public bool Execute(ArraySegment<string> arguments, ICommandSender sender, out string response)
        {
            if (!sender.CheckPermission(PlayerPermissions.ServerConsoleCommands))
            {
                response = "你没有权限执行此命令";
                return false;
            }

            if (ModuleManager.Plugins.TryGetFirst(p => p.Instance.Id == arguments.At(0), out var plugin))
            {
                if (plugin.Instance.CanUnload)
                {
                    ModuleManager.UnloadPlugin(arguments.At(0));
                    response = "已卸载对应插件";
                    return true;
                }
                else
                {
                    response = "无法卸载此插件，该插件被标明了无法卸载，" +
                               $"可能由于该程序集包含加载其他程序集而避免更新时程序集标识不同而出现{nameof(InvalidCastException)}问题，请使用冷重启";
                    return false;
                }
            }

            response = "未找到对应的插件！";
            return false;
        }

        public string Command { get; } = "unload";
        public string[] Aliases { get; } = Array.Empty<string>();
        public string Description { get; } = "卸载一个插件";
    }
}